% by YLX  
% 2021/6/11
% Version 5.0
% change log 
%% added timing function 
%% passed test

addpath functions;
% Global Variables are avaliable for ALL FUNCTIONS
% >>> global variables settings
global P J I ci cI r LAMBDA CURRENT PIEs
P = [.1, .5, .9]; % for test only
LAMBDA = 3;
ci=40;cI=200;r=100;
J = 3; I = 8;
%initTimer();
% end global settings <<<

% Line = xlsread('Simulated.xlsx'); 
% Line = load('sim_data.mat');
load('j_all.mat');
Line = j_all;
patient_number = sum(Line > 0); % equivalent to size(2)

genPoisson(patient_number);
genPIE(patient_number);

S = zeros(I, J);
% Profit = zeros(patient_number, I); % For What?

init_time = ftimer(); % set main clock

best_is = zeros(1, patient_number);
opt_profits = zeros(1,patient_number);
for n = 1:patient_number

    % fprintf("Arranging Patient No. %d \n", n);
    % start_time = ftimer(); % set loop clock

    CURRENT = n;
    j = Line(n);
    profits = zeros(1, I);
    for i = 1:I
        S_test = S;
        S_test(i, j) = S_test(i, j) + 1; % Replace rim & rimS
        Q = findQ(S_test); % size(Q) = [I, CURRENT]
        R = findR(Q);
        profits(i) = function_fQR(Q, R);
        % display(S_test)
        % display(Q)
        % display(R)
        % display(profits(i))
        % return;
    end
    % return;
    i = find(profits == max(profits));
    best_is(n) = i(1);
    i = i(1);
    S(i, j) = S(i, j) + 1;
    Q = findQ(S);
    R = findR(Q);
    opt_profits(n) = profits(i);
    % fprintf("    Time = %.2f seconds \n\n", ftimer()-start_time);
    
end
    

fprintf("\n\n Totle Time = %.1f seconds \n", ftimer()-init_time);

display(S)
%display(best_is)
load('arangement_i_paper');
%display(arangement_i_paper)

plot(1:patient_number,opt_profits, "linewidth", 1)
hold on 
grid on
%showTimer();